<script setup lang="ts">
import { reactive, getCurrentInstance } from "vue";

import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import upload from "@iconify-icons/ep/upload";
import plus from "@iconify-icons/ep/coin";
import AppUtil from "@/utils/AppUtil";

import { useRoute } from "vue-router";

//import log from "./comp/log.vue";
import Form from "@/components/Form.vue";
const route = useRoute();
defineOptions({
  name: "orders"
});
const config = reactive({
  listUrl: "/api/v1/orders",
  addUrl: "",
  editUrl: "",
  deleteUrl: "/api/v1/orders/delete",
  detailUrl: "",
  title: "订单",

  /**搜索条件 */
  searchForm: [
    {
      label: "门店",
      prop: "storeSid",
      type: "selectStoreSid",

      select: {
        placeholder: "请选择门店",
        options: [],
        filterable: true,
        remote: true,
        loading: false,
        remoteMethod(query, val) {
          // console.log("remoteMethod", query, val);
          AppUtil.request(
            {
              url: "/api/v1/stores?size=10",
              method: "get",
              params: {
                storesName: query || ""
              }
            },
            (res: any) => {
              res.data.records.map(item => {
                item.value = item.sid;
                item.name = item.storesName;
              });
              val.options = val.select.options = res.data.records;
              // console.log("remoteMethod", res.data)
            },
            b => {
              val.select.loading = false;
            }
          );

          // if (!val.options || !val.options.length) {
          //   val.select.loading = true;

          // } else if (query) {
          //   val.select.options = val.options.filter((val) => {
          //     return val.name.includes(query);
          //   });
          // } else {
          //   val.select.options = val.options;
          // }
        }
      }
    },
    //商品名称 goodsName
    {
      label: "商品名称",
      prop: "goodsName",
      type: "input",
      input: {
        type: "text"
      }
    },
    //订单状态 orderStatus
    {
      label: "订单状态",
      prop: "orderStatus",
      type: "select",
      select: {
        options: [
          { label: "待取货/待发货", value: 1 },
          { label: "已取货/已发货", value: 2 },
          { label: "配送中", value: 3 },
          { label: "已送达", value: 4 },
          { label: "已完成/待评价", value: 5 },
          { label: "已取消", value: 6 },
          { label: "已签收/待评价", value: 7 }
        ]
      }
    },
    //	订单类型 orderType
    //     3, "自提订单"
    // 4, "会员扫描下单"
    // 5, "商品扫描下单"
    {
      label: "订单类型",
      prop: "orderType",
      type: "select",
      select: {
        options: [
          { label: "同城订单", value: 1 },
          { label: "自提订单", value: 3 },
          { label: "物流订单", value: 2 },
          { label: "会员扫描下单", value: 4 },
          { label: "商品扫描下单", value: 5 }
        ]
      }
    },
    //收货人姓名 receiveName
    {
      label: "收货人姓名",
      prop: "receiveName",
      type: "input",
      input: {
        type: "text"
      }
    },
    //收货地址 receiveAddress
    {
      label: "收货地址",
      prop: "receiveAddress",
      type: "input",
      input: {
        type: "text"
      }
    },
    //收货人电话 receivePhone
    {
      label: "收货人电话",
      prop: "receivePhone",
      type: "input",
      input: {
        type: "text"
      }
    },
    //订单编号 orderSn
    {
      label: "订单编号",
      prop: "goodsOrderSn",
      type: "input",
      input: {
        type: "text"
      }
    }
  ],
  /**
   * 添加/编辑表单
   */
  editForm: [
    //状态 status
    {
      label: "审核",
      prop: "approval",
      type: "select",
      select: {
        options: [
          { label: "驳回", value: 2 },
          { label: "通过", value: 3 }
        ]
      },
      value: 2,
      rules: [{ required: true, message: "请选择状态", trigger: "blur" }],
      span: 12
    },

    //备注 note
    {
      label: "备注",
      prop: "note",
      type: "input",
      input: {
        type: "textarea",
        rows: 3
      },
      span: 24
    }
  ],
  rules: {},
  formData: {} as any,
  defaultData: {},

  /**
   * 表格列
   */
  columns: [
    {
      label: "订单编号",
      prop: "orderSn",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        return row.orderSn || row.goodsOrderSn;
      }
    },
    {
      label: "门店信息",
      prop: "store",
      minWidth: 200,
      slot: "store"
    },
    {
      label: "下单人/收货人",
      prop: "receive",
      minWidth: 180,
      slot: "receive"
    },
    {
      label: "订单信息",
      prop: "order",
      minWidth: 150,
      slot: "order"
    },

    // {
    //   label: "角色",
    //   prop: "roleName",
    //   width: 150
    // },

    {
      label: "操作",
      prop: "action",
      width: 150,
      slot: "operation",
      fixed: "right"
    }
  ]
});

const pData = reactive({
  /**
   * 表格数据
   */
  dataArr: [],
  /**
   * 表格加载
   */
  loading: false,
  /**请求中 */
  reqing: false,
  /**
   * 表格分页
   */
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  },

  searchData: {},
  showEdit: false,

  id: "",
  // item: {},

  /**角色列表 */
  roleArr: [],
  /**	支付状态：1待支付、2已支付uu费用、3已全部支付、4商品已支付、5退款中、6已退款 */
  payArr: [
    "",
    "待支付",
    "已支付uu",
    "已全部支付",
    "商品已支付",
    "退款中",
    "已退款"
  ],
  //	订单状态0订单创建 1待取货/待发货 2-已取货/已发货 3配送中 4-已送达 5-已完成/待评价 6-已取消 7-已签收/待评价,999-预订单
  statusObj: {
    1: "待取货/待发货",
    2: "已取货/已发货",
    3: "配送中",
    4: "已送达",
    5: "已完成/待评价",
    6: "已取消",
    7: "已签收/待评价",
    999: "预订单"
  },

  showDetail: false,
  item: {} as any
  //
});
const detailMsg = {
  orderSn: "订单编号",
  goodsOrderSn: "商品订单号",
  orderStatus: "订单状态",
  payStatus: "支付状态",
  amount: "订单金额",
  couponAmount: "优惠金额",
  uuFree: "uu费用",
  storeName: "门店名称",
  storeAddress: "门店地址",
  created: "创建时间",
  sendDistance: "配送距离",
  receiveName: "收货人姓名",
  receivePhone: "收货人电话",
  receiveAddress: "收货人地址"
};
const instance = getCurrentInstance();

function update_click(item) {
  console.log("update_click", item);
  config.formData = item;

  // config.editForm.map(item1 => {
  //   //处理封面初始化imgArr

  //   if (item1.type == "uploadOne") {
  //     item1.upload.fileArr = [
  //       {
  //         url: AppUtil.getAliImgUrlByH(item[item1.prop]),
  //         response: { code: 200, data: item[item1.prop] }
  //       }
  //     ];
  //   }
  // });
  // AppUtil.request(
  //   {
  //     url: "/api/v1/orders/" + item.sid,
  //     method: "get"
  //   },
  //   res => {}
  // );

  pData.showEdit = true;
}
function add_click() {
  if (config.formData.sid) {
    //移除选中的编辑数据，保留上次新增数据
    config.formData = JSON.parse(JSON.stringify(config.defaultData));
  }

  config.editForm.map(item1 => {
    //处理封面初始化imgArr
    if (item1.type == "uploadOne" || item1.type == "uploads") {
      item1.upload.fileArr = [];
    }
  });
  // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  pData.showEdit = true;
}

function handleSizeChange(val: number) {
  console.log(`${val} items per page`);
  pData.pagination.pageSize = val;
  reset_list();
}

function handleCurrentChange(val: number) {
  console.log(`current page: ${val}`);
  pData.pagination.currentPage = val;
  onSearch();
}
//请求轮播图数据
async function onSearch() {
  pData.loading = true;

  AppUtil.request(
    {
      url: config.listUrl,
      method: "get",
      params: {
        ...pData.searchData,
        current: pData.pagination.currentPage,
        size: pData.pagination.pageSize
      }
    },
    res => {
      console.log("onSearch", res);

      // res.data.records.map(item => {
      //   let imgArr = [];
      //   let bigArr = [];
      //   item.pg_hb &&
      //     item.pg_hb.map(item1 => {
      //       imgArr.push(AppUtil.getAliImgUrlByW(item1, 200));
      //       bigArr.push(AppUtil.imgHost + item1);
      //     });
      //   item.imgArr = imgArr;
      //   item.bigArr = bigArr;
      // });
      pData.dataArr = res.data.records;
      pData.pagination.total = res.data.total * 1;
      pData.pagination.currentPage = res.data.current * 1;
    },
    b => (pData.loading = false)
  );
}
onSearch();

// function handleDelete(item) {
//   AppUtil.request(
//     {
//       url: config.deleteUrl,
//       method: "PUT",
//       data: {
//         sidList: [item.sid]
//       }
//     },
//     res => {
//       onSearch();
//     }
//   );
// }

function search_click() {
  reset_list();
}
/**搜索第一页的数据 */
function reset_list() {
  pData.pagination.currentPage = 1;
  onSearch();
}
function submitForm() {
  submit_form();
  // if (pData.imgArr.length < 1) {
  //   return instance.proxy.$alert("请选择图片");
  // }
  // let img = pData.imgArr[0];
  // //图片已经上传过
  // if (img.response && img.response.code == 200) {
  //   return submit_form();
  // }
  // //上传图片
  // upload1.value!.submit();
}
/**
 * 提交表单
 */
function submit_form() {
  instance.proxy.$refs["vForm"].validate(valid => {
    if (!valid) return;
    pData.reqing = true;

    // return console.log("formData", config.formData);
    //config.formData 移除sid

    // formData.label = lArr;

    AppUtil.request(
      {
        url: "/api/v1/orders/" + config.formData.sid + "/review",

        method: "put",
        // url: config.addUrl,
        // method: "post",
        // data: formData
        data: {
          approval: config.formData.approval,
          sid: config.formData.sid,
          note: config.formData.note
        }
      },
      res => {
        // console.log("banner", res);
        instance.proxy.$message.success(
          config.formData.sid ? "修改成功" : "添加成功"
        );
        onSearch();
        pData.showEdit = false;
      },
      b => {
        pData.reqing = false;
      }
    );
  });
}

function detail_click(row) {
  AppUtil.request(
    {
      url: "/api/v1/orders/" + row.sid
    },
    res => {
      console.log("订单详情", res);
      pData.showDetail = true;
      //     amount: "订单金额",
      // couponAmount: "优惠金额",
      // uuFree: "uu费用",
      res.data.amount = (res.data.amount / 100).toFixed(2);
      res.data.couponAmount = (res.data.couponAmount / 100).toFixed(2);
      res.data.uuFree = (res.data.uuFree / 100).toFixed(2);

      pData.item = res.data;
    }
  );
}
function export_click() {
  pData.reqing = true;
  AppUtil.request(
    {
      url: "/api/v1/orders/export",
      method: "get",
      params: {
        ...pData.searchData,
        current: 1,
        size: 1000
      }
    },
    res => {
      instance.proxy.$message.success(res.data || "导出成功");
    },
    b => (pData.reqing = false)
  );
}
function refund_click(item) {
  console.log("item", item);
  ///v1/orders/{sid}/selfPickupOrderRefund
  AppUtil.request(
    {
      url: "/api/v1/orders/" + item.sid + "/selfPickupOrderRefund",
      method: "put"
    },
    res => {
      instance.proxy.$message.success("退款成功");
      onSearch();
    }
  );
}
function finish_click(item) {
  AppUtil.request(
    {
      url: "/api/v1/orders/" + item.sid + "/finish",
      method: "get"
    },
    res => {
      instance.proxy.$message.success("操作成功");
      onSearch();
    }
  );
}
</script>

<template>
  <div class="main">
    <el-form
      v-if="config.searchForm && config.searchForm.length > 0"
      :model="pData.searchData"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
      style="padding-bottom: 5px"
      :inline="true"
    >
      <el-form-item
        v-for="(item, i) in config.searchForm"
        :key="i"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-if="item.type === 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="(option, j) in item.select.options"
            :key="j"
            :label="option.label || option.name"
            :value="option.value || option.id"
          />
        </el-select>
        <el-select
          v-if="item.type == 'selectStoreSid'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          :multiple="item.select?.multiple || false"
          :placeholder="item.select?.placeholder"
          clearable
          :remote-method="q => item.select?.remoteMethod(q, item)"
          remote-show-suffix
          filterable
          :remote="item.select?.remote || false"
          :loading="item.select?.loading || false"
        >
          <el-option
            v-for="(item2, index2) in item.select.options"
            :key="index2"
            :label="item2.label || item2.name"
            :value="item2.value || item2.id"
          />
        </el-select>
        <el-input
          v-else-if="item.type === 'input'"
          v-model="pData.searchData[item.prop]"
          :placeholder="item.input.placeholder"
          clearable
        />
        <el-date-picker
          v-else-if="item.type === 'datetimerange'"
          v-model="pData.searchData[item.prop]"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 360px"
        />
        <el-cascader
          v-else-if="item.type === 'cascader'"
          v-model="pData.searchData[item.prop]"
          style="width: 100%"
          :props="item.cascader.props"
          :options="item.cascader.options"
          clearable
          :placeholder="item.cascader.placeholder"
          :show-all-levels="item.cascader.showAllLevels || false"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="pData.loading"
          @click="search_click"
        >
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      :title="config.title + '管理'"
      :columns="config.columns"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          style="margin-left: 1rem"
          type="danger"
          :loading="pData.reqing"
          :icon="useRenderIcon(plus)"
          @click="export_click"
        >
          导出商品
        </el-button>
        <el-button
          v-if="config.addUrl"
          type="primary"
          :icon="useRenderIcon(upload)"
          @click="add_click"
        >
          新增{{ config.title }}
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          :data="pData.dataArr"
          :columns="dynamicColumns"
          :loading="pData.loading"
          :size="size"
          :pagination="pData.pagination"
          :paginationSmall="size === 'small' ? true : false"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #store="{ row }">
            <div style="display: flex">
              <img
                :src="AppUtil.getAliImgUrlByH(row.storeLogo)"
                style="width: 50px; height: 50px; margin-right: 10px"
              />
              <div>
                <div>门店id：{{ row.storeId }}</div>
                <div>店名：{{ row.storeName }}</div>
                <div>地址：{{ row.storeAddress }}</div>
              </div>
            </div>
          </template>
          <template #receive="{ row }">
            <div>下单人：<span style="font-weight: bold">{{ row.downOrderPeopleName }}</span>  [ {{ row.downOrderPeoplePhone }} ] </div>
            <div  v-if="row.receiveName || row.receivePhone">收货人：<span style="font-weight: bold">{{ row.receiveName }}</span>  [ {{ row.receivePhone }} ] </div>
            <div v-if="row.receiveAddress">收货地址：{{ row.receiveAddress }}</div>
          </template>
          <template #order="{ row }">
            <div>金额：{{ (row.amount / 100).toFixed(2) }}</div>
            <div>优惠减免：{{ (row.couponAmount/ 100).toFixed(2) }}</div>
            <div>UU费用：{{ (row.uuFree / 100).toFixed(2) }}</div>
            <div>支付状态：{{ pData.payArr[row.payStatus] }}</div>
            <div>订单状态：{{ pData.statusObj[row.orderStatus] }}</div>
            <div>创建时间：{{ row.created }}</div>
          </template>
          <template #status="{ row }">
            <div style="margin-top: 5px">
              <el-tag
                :type="row.status == 0 ? 'success' : 'danger'"
                size="small"
              >
                {{ row.status == 0 ? "正常" : "禁用" }}
              </el-tag>
            </div>
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              type="primary"
              size="small"
              @click="detail_click(row)"
            >
              查看详情
            </el-button>
            <el-popconfirm
              v-if="row.orderStatus == 1 && row.orderType == 2"
              title="是否确认完成此订单"
              @confirm="finish_click(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="warning"
                  size="small"
                >
                  完成
                </el-button>
              </template>
            </el-popconfirm>

            <el-popconfirm
              v-if="
                row.payStatus > 1 && row.payStatus < 5 && row.orderType >= 3
              "
              title="是否确认退款这个订单"
              @confirm="refund_click(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                >
                  退款
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-dialog
      v-model="pData.showDetail"
      align-center
      title="订单详情"
      width="65vw"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto">
        <el-descriptions class="margin-top" :column="3" border>
          <el-descriptions-item v-for="(label, key) in detailMsg" :key="key">
            <template #label>
              <div class="cell-item">
                {{ label }}
              </div>
            </template>
            <div v-if="key == 'orderStatus'">
              {{ pData.statusObj[pData.item[key]] }}
            </div>
            <div v-else-if="key == 'payStatus'">
              {{ pData.payArr[pData.item[key]] }}
            </div>

            <div v-else>
              {{ pData.item[key] }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 1rem">
          <el-table
            :data="pData.item.goods"
            :border="true"
            :header-cell-style="{ background: '#f5f7fa' }"
            :cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="goodsImg">
              <template #default="scope">
                <img
                  :src="AppUtil.getAliImgUrlByH(scope.row.goodsImg)"
                  style="width: 60px; height: 60px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" />
            <el-table-column prop="goodsNum" label="数量" />
            <el-table-column prop="goodsPrice" label="单价">
              <template #default="scope">
                {{ (scope.row.goodsPrice / 100).toFixed(2) }}/{{
                  scope.row.goodsUnit
                }}
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="小计">
              <template #default="scope">
                {{ (scope.row.totalPrice / 100).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showDetail = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="pData.showEdit"
      align-center
      :title="`${config.formData.sid ? '修改' : '新增'}${config.title}`"
      :width="700"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="vForm" v-model="config" />
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showEdit = false">取消</el-button>
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitForm()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
